package com.xunfang.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xunfang.bean.Building;
import com.xunfang.bean.House;
import com.xunfang.bean.dto.BuildQueryDTO;
import com.xunfang.bean.vo.PageVo;
import com.xunfang.mapper.BuildingMapper;
import com.xunfang.service.IBuildingService;
import com.xunfang.service.IHouseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;

/**
 * @author yellow Docter
 * @date 2023 -11-02
 * @desc
 */
@Service
public class BuildingService implements IBuildingService {

    @Autowired
    private BuildingMapper buildingMapper;

    @Autowired
    private IHouseService houseService;

    //事务:  多个sql语句同事执行、要不都执行成功、有一条sql执行失败、会进行数据回滚
    @Transactional  //开启事务    底层 封装了 apo  封装了事务
    @Override
    public boolean batchBuild(List<Integer> ids) {
        return buildingMapper.batchBuild(ids) > 0 ;
    }

    @Override
    public List<Building> findBuildsAll() {
        BuildQueryDTO buildQueryDTO = new BuildQueryDTO();
        return buildingMapper.findBuilds(buildQueryDTO);
    }



    @Override
    public boolean addBuildById(Building building) {
        return buildingMapper.addBuild(building) > 0;
    }

    @Override
    public boolean updateBuildById(Building building) {
        return buildingMapper.updateBuild(building) > 0;
    }

    @Override
    public PageVo findBuilds(Integer currentPage, Integer pageSize, BuildQueryDTO buildQueryDTO) {

        // 01 调用分页的方法
        Page<Building> pageInfo =  PageHelper.startPage(currentPage,pageSize).doSelectPage(()->{
            buildingMapper.findBuilds(buildQueryDTO);
        });

        //02 拿到 分页对象 Page

        long total = pageInfo.getTotal();
        List<Building> list = pageInfo.getResult();
        //03 返回结果
        PageVo pageVo = new PageVo();
        pageVo.setTotal(total);
        pageVo.setData(list);
        return pageVo;

    }

    @Override
    public boolean removeBuildById(Integer id) {

        //删除
        //判断 house中是否有 引用 ( 如果有不能删除 )
        List<House> houses = houseService.findHousesByBuildingId(id);

        //判断    可以删除
        if (CollectionUtils.isEmpty(houses)){
            return buildingMapper.deleteBuildsById(id) > 0 ;
        }
        return false;
    }

}
